// pages/dataEntry/dataEntry.jsconst app = getApp()
var http = require('../../../../service/http.js');
var getTime = require('../../../../utils/util.js');
var wechat = require('../../../../utils/wechat.js');
let app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    select: false,
    tihuoWay: '',
    step: 1,
    // 1
    policy_num: "",
    report_num: "",
    insurance_type: "",
    insurance_type_name: "",
    ui_id: "",
    end_at: "",
    username: "",
    mobile: "",
    company_name: "",
    // 2
    goods_type: '',
    goods_name: '',
    goods_num: '',
    good_price: '',
    good_pg_price: '',

    // 3
    damage_at: '',
    damage_result: '',
    address: '',
    address_detail: '',
    other_report: [],
    // 4
    present_at: '',
    goods_list: [],
    goods_desc: '',
    present_img: [],
    present_video: [],
    // present_video: [],
    // 5
    should_at: '',
    rem_company: '',
    linkman: '',
    connect_phone: '',
    // 6
    author_report: [],

    newTime: '',
    insuranceTypeList: [],
    goodsTypeList: [],
    goodsTypeIndex: '',
    insuranceTypeIndex: '',
    damageResultNum: 0,
    damageResultMaxNum: 200,
    goodsDescNum: 0,
    goodsDescMaxNum: 200,
    landed: false,
    showModal: false,
    showWebView: false
  },


  delAuthorReportFile(e) {
    var author_report = this.data.author_report;
    var arr = [];
    for (var i = 0; i < author_report.length; i++) {
      console.log(e.currentTarget.dataset.index)
      if (i == e.currentTarget.dataset.index) {
      } else {
        arr.push(author_report[i])
      }
    }
    // imgList =
    this.setData({
      author_report: arr
    })
  },
  delGoodsFile(e) {
    var goods_list = this.data.goods_list;
    var arr = [];
    for (var i = 0; i < goods_list.length; i++) {
      console.log(e.currentTarget.dataset.index)
      if (i == e.currentTarget.dataset.index) {
      } else {
        arr.push(goods_list[i])
      }
    }
    // imgList =
    this.setData({
      goods_list: arr
    })
  },
  delSanfile(e) {
    console.log(e)
    var other_report = this.data.other_report;
    var arr = [];
    for (var i = 0; i < other_report.length; i++) {
      console.log(e.currentTarget.dataset.index)
      if (i == e.currentTarget.dataset.index) {
      } else {
        arr.push(other_report[i])
      }
    }
    // imgList =
    this.setData({
      other_report: arr
    })
  },
  delImg(e) {
    console.log(e)
    var present_img = this.data.present_img;
    var arr = [];
    for (var i = 0; i < present_img.length; i++) {
      console.log(e.currentTarget.dataset.index)
      if (i == e.currentTarget.dataset.index) {
      } else {
        arr.push(present_img[i])
      }
    }
    // imgList =
    this.setData({
      present_img: arr
    })
  },
  delVideo(e) {
    console.log(e)
    var present_video = this.data.present_video;
    var arr = [];
    for (var i = 0; i < present_video.length; i++) {
      console.log(e.currentTarget.dataset.index)
      if (i == e.currentTarget.dataset.index) {
      } else {
        arr.push(present_video[i])
      }
    }
    this.setData({
      present_video: arr
    })
  },
  // nextStep(e) {
  //   // if (this.data.step == '1') {
  //   //   if (!this.data.policy_num || !this.data.report_num || !this.data.insurance_type) {
  //   //     wx.showToast({
  //   //       title: '请填写完整信息',
  //   //       icon: 'none'
  //   //     })
  //   //     return
  //   //   }
  //   // }
  //   // if (this.data.step == '2') {
  //   //   if (!this.data.goods_type || !this.data.goods_name || !this.data.goods_num || !this.data.good_price || !this.data.good_pg_price) {
  //   //     wx.showToast({
  //   //       title: '请填写完整信息',
  //   //       icon: 'none'
  //   //     })
  //   //     return
  //   //   }
  //   // }

  //   http.postReq('/index/index/getInsuranceType', {
  //     now_status: this.data.step,
  //     // 1
  //     policy_num: this.data.policy_num,
  //     // 2
  //     goods_type: this.data.goods_type,
  //     goods_name: this.data.goods_name,
  //     goods_num: this.data.goods_num,
  //     good_price: this.data.good_price,
  //     good_pg_price: this.data.good_pg_price,

  //     // 3
  //     damage_at: this.data.damage_at,
  //     damage_result: this.data.damage_result,
  //     address: this.data.address ? this.data.address.join(',') : '',
  //     address_detail: this.data.address_detail,
  //     other_report: this.data.other_report,
  //     // 4
  //     present_at: this.data.present_at,
  //     goods_list: this.data.goods_list,
  //     goods_desc: this.data.goods_desc,
  //     present_img: this.data.present_img ? this.data.present_img.join(',') : '',
  //     present_video: this.data.present_video ? this.data.present_video.join(',') : '',
  //     // 5
  //     should_at: this.data.should_at,
  //     rem_company: this.data.rem_company,
  //     linkman: this.data.linkman,
  //     connect_phone: this.data.connect_phone,

  //   }, res => {

  //     if (e.target.dataset.index == '6') {
  //       // 提交
  //       wx.showToast({
  //         title: '提交成功',
  //         duration: 1500
  //       })
  //       setTimeout(() => {
  //         wx.navigateTo({
  //           url: '../../index',
  //         })
  //       }, 1500)
  //     } else {
  //       this.setData({
  //         step: JSON.parse(e.target.dataset.index) + 1
  //       })
  //     }
  //   })

  // },
  one_good_pg_price(e) {
    this.setData({
      good_pg_price: e.detail.value
    })
  },
  one_policy_num(e) {
    this.setData({
      policy_num: e.detail.value
    })
  },
  one_report_num(e) {
    this.setData({
      report_num: e.detail.value
    })
  },
  two_goods_name(e) {
    this.setData({
      goods_name: e.detail.value
    })
  },
  two_goods_num(e) {
    this.setData({
      goods_num: e.detail.value
    })
  },
  two_good_price(e) {
    this.setData({
      good_price: e.detail.value
    })
  },
  //受损原因
  three_damage_result(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      damageResultNum: e.detail.value.length,
      damage_result: e.detail.value
    })
  },
  three_address_detail(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      address_detail: e.detail.value
    })
  },
  four_goods_desc(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      goodsDescNum: e.detail.value.length,
      goods_desc: e.detail.value
    })
  },
  five_rem_company(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      rem_company: e.detail.value
    })
  },
  five_linkman(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      linkman: e.detail.value
    })
  },
  five_connect_phone(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      connect_phone: e.detail.value
    })
  },
  lookTemplate() {
    wx.navigateTo({
      url: '../template/template',
    })
  },
  //选择时间
  bindShouldChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      should_at: e.detail.value
    })
  },
  bindPresentChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      present_at: e.detail.value
    })
  },
  bindDamageChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      damage_at: e.detail.value
    })
  },
  //选择省市区
  bindAddressChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      address: e.detail.value
    })
  },
  //货物类别
  getGoodsType(goodtype) {
    http.getReq('/index/index/goodsType',{}, res => {
      if (goodtype) {
        res.data.type_list.forEach((i,key)=> {
          if (i.gt_id == goodtype) {
            this.setData({
              goods_type: i.gt_id,
              goodsTypeIndex: key
            })
          }
        });
      }
      this.setData({
        goodsTypeList: res.data.type_list
      })
    })
  },
  //保险种类
  getInsuranceType(chosedid) {
    chosedid = chosedid ? chosedid :'';
    var chose_arr=chosedid.split(",");
    http.getReq('/index/index/getInsuranceType',{}, res => {
      var insuranceTypeSelected = [];
      var insuranceTypeSelectedID = [];
      res.data.type_list.forEach(i =>{
        i.checked = false
        if(chose_arr.indexOf(i.it_id) >-1){
            i.checked = true;
            insuranceTypeSelected.push(i.it_name);
            insuranceTypeSelectedID.push(i.it_id);
        }
      });
      this.setData({
        insuranceTypeSelected: insuranceTypeSelected.join(','),
        insuranceTypeSelectedID: insuranceTypeSelectedID.join(','),
        insuranceTypeList: res.data.type_list,
      })
    })
  },
  goodsTypeList(e) {
    let typeList = this.data.goodsTypeList;
    this.setData({
      goodsTypeIndex: e.detail.value,
      goods_type: typeList[e.detail.value].gt_id
    })
  },
  insuranceTypeList(e) {
    let typeList = this.data.insuranceTypeList;
    this.setData({
      insuranceTypeIndex: e.detail.value,
      insurance_type: typeList[e.detail.value].it_id
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.tabBar();
    http.getReq('/index/NewNeed/getInsurerFirst', {
      p_id: options.p_id,
      type: options.type
    }, res => {
      this.setData({
        company_name: res.data.company_name,
        mobile: res.data.mobile,
        policy_num: res.data.policy_num || '',
        report_num: res.data.report_num || '',
        insurance_type: res.data.insurance_type || '',
        ui_id: res.data.ui_id || '',
        end_at: res.data.end_at || '',
        username: res.data.username || '',
        step:options.step,
        p_id:options.p_id
        // newTime: getTime(new Date())
      })
    })
    

    if (options.p_id){
      http.getReq('/index/NewNeed/getInsurerFirst', {
        p_id: options.p_id,
        type: options.type
      }, res => {
          let _data = res.data
          let _this = this;
          this.getInsuranceType(_data.goods_info.insurance_type)
          this.getGoodsType(_data.goods_info.goods_type)
          this.setData({
            // 2
            goods_type: _data.goods_info.goods_type ? _data.goods_info.goods_type : '',
            goods_name: _data.goods_info.goods_name ? _data.goods_info.goods_name : '',
            goods_num: _data.goods_info.goods_num ? _data.goods_info.goods_num : '',
            good_price: _data.goods_info.good_price ? _data.goods_info.good_price : '',
            good_pg_price: _data.goods_info.good_pg_price ? _data.goods_info.good_pg_price : '',
            insurance_type_name: _data.goods_info.insurance_type_name ? _data.goods_info.insurance_type_name : '',
            // 3
            damage_at: _data.goods_info.damage_at ? _data.goods_info.damage_at : '',
            damage_result: _data.goods_info.damage_result ? _data.goods_info.damage_result : '',
            address: [_data.goods_info.omit, _data.goods_info.city, _data.goods_info.classify],
            address_detail: _data.goods_info.address_detail ? _data.goods_info.address_detail : '',
            other_report:  _data.goods_info.other_report.length>0 ?  _data.goods_info.other_report: [],
            // 4
            present_at: _data.goods_info.present_at ? _data.goods_info.present_at : '',
            goods_list: _data.goods_info.goods_list,
            goods_desc: _data.goods_info.goods_desc ? _data.goods_info.goods_desc : '',
            present_img: _data.goods_info.present_img,

            /* 一片天空修改  接口返回数组格式  无需 分割  start*/
            present_video: _data.goods_info.present_video ? _data.goods_info.present_video : [],
            /* 一片天空修改  end*/

            // 5
            should_at: _data.goods_info.should_at ? _data.goods_info.should_at : '',
            rem_company: _data.goods_info.rem_company ? _data.goods_info.rem_company : '',
            linkman: _data.goods_info.linkman ? _data.goods_info.linkman : '',
            connect_phone: _data.goods_info.connect_phone ? _data.goods_info.connect_phone : '',
            // 6
          })
      })
      return false;
      this.getInsuranceType() //出险险种
      this.getGoodsType() //货物类别
    }
  },
  bindShowMsg() {
    this.setData({
      select: !this.data.select
    })
  },
  mySelect(e) {
    var name = e.currentTarget.dataset.name
    this.setData({
      tihuoWay: name,
      select: false
    });
  },
  lastSubmit () {
    http.postReq('/index/recordor/recordConfir', {
      policy_num: this.data.policy_num,
      should_at: this.data.should_at,
      rem_company: this.data.rem_company,
      linkman: this.data.linkman,
      connect_phone: this.data.connect_phone,
    }, res => {
      // 提交
      wx.showToast({
        title: '提交成功',
        duration: 1500
      })
      setTimeout(() => {
        wx.navigateTo({
          // url: '../insuranceEntryList/insuranceEntryList',
          url: '/pages/index/index',
        })
      }, 1500)
    })
  },
  nextStep(e) {
    // if (e.target.dataset.index == '5') {
    //   let _this = this
    //   wx.showModal({
    //     title: '提示',
    //     content: '资料先递交保险公司确认，确认后将回复给您',
    //     success(res) {
    //       if (res.confirm) {
    //         _this.lastSubmit()
    //       }
    //     }
    //   })
    //   return false
    // }
    if (e.target.dataset.index == '5') {
      var step = JSON.parse(this.data.step) + 1
      wx.navigateTo({
        url: '/pages/index/bbxr/checkData/writeData/writeData?p_id=' + this.data.p_id + '&step=' + step,
      })
    }
    var goods_list = this.data.goods_list.map(i => i.url);
    http.postReq('/index/NewNeed/saveInsurer', {
      step: this.data.step,
      // 1
      policy_num: this.data.policy_num,
      report_num: this.data.report_num,
      insurance_type: this.data.insurance_type,
      p_id: this.data.p_id,
      // 2
      goods_type: this.data.goods_type,
      goods_name: this.data.goods_name,
      goods_num: this.data.goods_num,
      good_price: this.data.good_price,
      good_pg_price: this.data.good_pg_price,
      // 3
      damage_at: this.data.damage_at,
      damage_result: this.data.damage_result,
      omit: this.data.address && this.data.address.length > 0 ? this.data.address[0] : '',
      city: this.data.address && this.data.address.length > 0 ? this.data.address[1] : '',
      classify: this.data.address && this.data.address.length > 0 ? this.data.address[2] : '',
      address_detail: this.data.address_detail,
      other_report: JSON.stringify(this.data.other_report),
      // 4
      present_at: this.data.present_at,
      goods_list: JSON.stringify(this.data.goods_list),
      goods_desc: this.data.goods_desc,
      present_img: this.data.present_img && this.data.present_img.length ? JSON.stringify(this.data.present_img) : '',
      present_video: this.data.present_video && this.data.present_video.length ? JSON.stringify(this.data.present_video) : '',
      // 5
      should_at: this.data.should_at,
      rem_company: this.data.rem_company,
      linkman: this.data.linkman,
      connect_phone: this.data.connect_phone,

    }, res => {
      //  else {
        if (e.target.dataset.index == 5) {
          this.setData({
            step: JSON.parse(e.target.dataset.index),
          })
        } else {
          this.setData({
            step: JSON.parse(e.target.dataset.index) + 1
          })
        }
        
      // }
      // if (e.target.dataset.index == '5') {
      //   // 提交
      //   wx.showToast({
      //     title: '提交成功',
      //     duration: 1500
      //   })
      //   setTimeout(() => {
      //     wx.navigateTo({
      //       url: '../insuranceEntryList/insuranceEntryList',
      //     })
      //   }, 1500)
      // } else {
      //   this.setData({
      //     step: JSON.parse(e.target.dataset.index) + 1
      //   })
      // }
    })

  },
  preStep(e) {
    this.setData({
      step: JSON.parse(e.target.dataset.index) - 1
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (!this.data.landed) {
      this.setData({landed: true});
      return;
    }
    if(!this.data.showWebView) {
      this.setData({showWebView: false});
      return;
    }
    http.getReq('/index/user/getRole',{},_res=>{
      http.postReq('/index/upload/get_upload_url', {
        phone: _res.data.phone
      }, res => {
        if (res.data.url) {
        var inList = false;
        var url = res.data.url;
        this.data.goods_list.forEach(i => {
          if (i.url === url) {
          inList = true;
        }
      });
        if (!inList) {
          var name = res.data.url_name;
          var list = this.data.goods_list;
          list.push({url: url, url_name: name});
          this.setData({goods_list: list});
          console.log(this.data.goods_list)
        }
      }
    });
  })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  authorReportFile() {
    wechat.chooseImage()
      .then(d => {
        let { path, size } = d.tempFiles[0];
        // let params = this.data.present_img;
        // params.push(path)
        // this.setData({
        //   tempImagePath: path,
        // });
        // console.log(path)
        return wechat.uploadFile("/index/Upload/index", path, "avatar")
      })
      .then(d => {
        let res = JSON.parse(d.data)
        let author_report = this.data.author_report
        author_report.push(res.data.url)
        console.log(author_report)
        this.setData({
          author_report: author_report
        })
      })
      .catch(e => {
        console.log(e);
      })
  },
  // 第三方报告
  sanfile() {
    wechat.chooseImage()
      .then(d => {
        wx.showLoading({title: '上传中', mask: true});
        let { path, size } = d.tempFiles[0];
        // let params = this.data.present_img;
        // params.push(path)
        // this.setData({
        //   tempImagePath: path,
        // });
        // console.log(path)
        return wechat.uploadFile("/index/Upload/index", path, "avatar")
      })
      .then(d => {
        wx.hideLoading();
        let res = JSON.parse(d.data)
        let other_report = this.data.other_report
        other_report.push(res.data.url)
        console.log(other_report)
        this.setData({
          other_report: other_report
        })
      })
      .catch(e => {
        wx.hideLoading();
        console.log(e);
      })
  },
  // 货品清单
  goodsFile() {
    this.setData({showWebView: true});
    http.getReq('/index/user/getRole',{}, res=>{
      wx.navigateTo({
        url: '../../../public/webView/webView?phone='+res.data.phone
      });
    })
    // wechat.chooseImage()
    //   .then(d => {
    //     let { path, size } = d.tempFiles[0];
    //     // let params = this.data.present_img;
    //     // params.push(path)
    //     // this.setData({
    //     //   tempImagePath: path,
    //     // });
    //     // console.log(path)
    //     return wechat.uploadFile("/index/Upload/index", path, "avatar")
    //   })
    //   .then(d => {
    //     let res = JSON.parse(d.data)
    //     let goods_list = this.data.goods_list
    //     goods_list.push(res.data.url)
    //     console.log(goods_list)
    //     this.setData({
    //       goods_list: goods_list
    //     })
    //   })
    //   .catch(e => {
    //     console.log(e);
    //   })
  },
  camera(e) {
    let { type } = e.target.dataset;
    this.setData({
      type
    })
    console.log("开始上传准备", type == "chooseImage" ? "图片" : "视频");
    // 拍照
    if (type == "chooseImage") {
      console.log("选择图片");
      wechat.chooseImage()
        .then(d => {
          wx.showLoading({title: '上传中', mask: true});
          let { path, size } = d.tempFiles[0];
          // let params = this.data.present_img;
          // params.push(path)
          // this.setData({
          //   tempImagePath: path,
          // });
          // console.log(path)
          return wechat.uploadFile("/index/Upload/index", path, "avatar")
        })
        .then(d => {
        wx.hideLoading();
          let res = JSON.parse(d.data)
          let present_img = this.data.present_img
          present_img.push(res.data.url)
          console.log(present_img)
          this.setData({
            present_img: present_img
          })
        })
        .catch(e => {
        wx.hideLoading();
          console.log(e);
        })
    }
    // 录视频
    else if (type == "chooseVideo") {
        /* 一片天空改动  上传视屏  satrt 2018:12:23 */
        var  _this = this;
        wx.chooseVideo({
            sourceType: ['album', 'camera'],
            maxDuration: 60,
            camera: 'back',
            success(res) {
                wx.showLoading({title: '上传中', mask: true});
                var size = res.size ; 
                var tempFilePath = res.tempFilePath;
                if (size > 10 * 1024 * 1024){ 
                    wx.showToast({title: '视频不可超过10M',icon: 'none',duration: 2000}); return;
                }
                wechat.uploadFile("/index/Upload/index", tempFilePath, "avatar").then(d => {
                    wx.hideLoading();
                    var re = JSON.parse(d.data);
                    if(re.code == 200){
                        var present_video = _this.data.present_video
                        present_video.push(re.data.url)
                        _this.setData({present_video: present_video})
                    }else{
                        wx.showToast({title: '视频上传失败',icon: 'none',duration: 2000});
                    }
                });    
            },
            fail(res){
                wx.showToast({title: '视频上传失败,文件大小不可超过10M',icon: 'none',duration: 2000});
            }
        })
        /* 一片天空改动  上传视屏  end 2018:12:23 */
    }
  }
})
